using hao_Common.Dapper.Db;
using hao_Common.Dapper.Repository;
using hao_Reppsitory.Product;
using hao_Reppsitory;
using Product.Service;
using hao_Jwt;
using Microsoft.OpenApi.Models;
using hao_Common.Consul.Extensions;
using hao_Common.AutoMapper.Extensions; // 添加AutoMapper扩展引用
using hao_Common.Logging.Extensions;
using System.Reflection;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// 配置Serilog日志
builder.Host.AddSerilog(builder.Configuration);

// Add services to the container.
builder.Services.AddControllers();

// 添加日志服务
builder.Services.AddLogging(builder.Configuration);

// 添加AutoMapper服务
builder.Services.AddAutoMapperService(
    typeof(Program).Assembly, // 当前程序集
    typeof(hao_Common.AutoMapper.Profiles.BaseProfile).Assembly // AutoMapper配置程序集
);

// 添加JWT认证服务
builder.Services.AddJwtAuthentication(builder.Configuration);

// 添加Consul服务注册
builder.Services.AddConsul(builder.Configuration);

// 添加健康检查服务
builder.Services.AddHealthChecks();

// 添加CORS服务，允许所有来源
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

// 配置Swagger支持JWT Bearer认证
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo 
    { 
        Title = "Hao Product API", 
        Version = "v1",
        Description = "商品管理API接口文档"
    });
    
    // 添加XML注释文件支持
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath, true);
    }
    
    // 添加JWT Bearer认证定义
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        Scheme = "Bearer"
    });
    
    // 添加安全要求
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});

builder.Services.AddSingleton<IDbConnectionFactory, DapperDbConnectionFactory>();
builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(DapperGenericRepository<>));

// 注册HttpClient用于服务间调用
builder.Services.AddHttpClient();

// 注册HttpHelper服务
builder.Services.AddScoped<hao_Common.Http.Interfaces.IHttpHelper, hao_Common.Http.Services.HttpHelper>();

// 注册Product相关仓储和服务
builder.Services.AddScoped<IProductRepository, ProductRepository>();
builder.Services.AddScoped<IProductImageRepository, ProductImageRepository>();
builder.Services.AddScoped<IProductService, ProductService>();
// 注册Category相关仓储和服务
builder.Services.AddScoped<ICategoryRepository, CategoryRepository>();
builder.Services.AddScoped<ICategoryService, CategoryService>();
// 注册ProductComment相关仓储和服务
builder.Services.AddScoped<IProductCommentRepository, hao_Reppsitory.Product.ProductCommentRepository>();
builder.Services.AddScoped<IProductCommentLikeRepository, hao_Reppsitory.Product.ProductCommentLikeRepository>();
builder.Services.AddScoped<IProductCommentService, ProductCommentService>();

var app = builder.Build();

// 测试数据库连接
var factory = app.Services.GetRequiredService<IDbConnectionFactory>() as DapperDbConnectionFactory;
if (factory != null && !factory.TestConnection())
{
    throw new Exception("数据库连接失败，请检查连接字符串配置！");
}

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// 添加请求日志中间件
app.UseRequestLogging();

// 添加健康检查端点
app.MapHealthChecks("/health");

// 添加认证和授权中间件
app.UseAuthentication();
app.UseAuthorization();

// 启用CORS中间件，必须在UseAuthorization和MapControllers之前
app.UseCors("AllowAll");

// 配置静态文件中间件，允许访问wwwroot下的静态资源（如商品图片）
app.UseStaticFiles();
app.MapControllers();

app.Run();